<?php
namespace app\api\controller;
use app\service\LogService;

class Upload extends Base
{
  /* 聊天上传接口 */
  public function chat () {
    $type = input('type')?input('type'):false;
    if($type) {
      $type = strtolower($type);
    }
    if(request()->isPost()){
      $ret = model('qiniu')->upload('chat',$type);
      if(!$ret) {
        $this->ajax(202,'上传失败');
      }
      $this->ajax(200,'success',[
        //'path' => $ret['key'],
        'src' => tomedia($ret['key'])
      ]);
    }
  }

  /* media下载接口 */
  public function media () {
    $mediaId = input('mediaId');
    if(!$mediaId) {
      $this->ajax(202,'mediaId is null');
    }
    $stream = $this->officialAccount->media->get($mediaId);
    if ($stream instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
      $path = ROOT_PATH."public/cache/";
      $name = uniqid().time().".amr";
      $stream->saveAs($path, $name);
      $res = model('qiniu')->local2remote($path.$name,'voice',true);
      if(!$res) {
        $this->ajax(202,'上传失败,请重试');
      }
      //amr转mp3
      $saveName = str_replace('.','',$_SERVER['SERVER_NAME'])."/voice/".date('Ymd')."/".date('His').rand(0, 9999).'.mp3';
      model('qiniu')->amr2mp3($res['key'],$saveName);
      $this->ajax(200,'success',[
        'src' => tomedia($saveName),
        'mediaId' => $mediaId
      ]);
    }else{
      $this->ajax(202,'资源不存在');
    }
  }

  

}
